package com.xb.cloud.configcenter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xb.cloud.common.redis.CacheUtil;
import com.xb.cloud.common.util.StringUtils;
import com.xb.cloud.product.service.client.ConfigCenterService;
import com.xb.cloud.product.service.client.bo.ConfigCenterBo;

//TODO: 此类现在在servlet初始化时进行加载，在网关用spring获取到该类。后期拆分时需要考虑在什么时候加载，哪个项目加载，如何读取数据。
// 如：后期在网关启动时加载，网关没法直接读取数据库怎么处理

@Component("DBConfigLoader")
public class DBConfigLoader {
	private static final Logger LOGGER = LoggerFactory.getLogger(DBConfigLoader.class);

	@Resource
	ConfigCenterService configCenterService;

	public void load() {
		LOGGER.info("初始化加载数据库配置信息。。。。。");

		CacheUtil.del("configCenter");

		Map<String, String> configMap = new HashMap<>();
		List<ConfigCenterBo> configList = configCenterService.getAllConfig();
		for (ConfigCenterBo configCenterBo : configList) {
			String schema = configCenterBo.getConfigSchema();
			String key = configCenterBo.getConfigKey();
			String value = configCenterBo.getConfigValue();
			Byte type = configCenterBo.getType();
			if (type == 1 && StringUtils.isNotEmpty(schema)) {
				configMap.put(schema + "-" + key, value);
			} else {
				configMap.put(key, value);
			}
		}

		CacheUtil.hmset("configCenter", configMap);
	}
}
